import logging

from config import settings
from core.book_parser import BookParser
from core.vocab_processor import VocabularyProcessor
from core.file_manager import FileManager
from utils.logger import VocabLogger
from config.exceptions import *
import pandas as pd

def main():
    logger = VocabLogger()
    try:
        # 初始化
        logger.log("启动电子书词汇提取系统")

        # 文件处理
        book_parser = BookParser(settings.EPUB_PATH)
        book_parser.validate_and_load()
        # book_parser.load_book()

        # 词汇处理
        processor = VocabularyProcessor()
        known_words = FileManager.load_known_words()

        # 处理章节
        results = {}
        chapters = book_parser.extract_chapters()
        for idx, (title, text) in enumerate(chapters, 1):
            vocab = processor.process_book(text, known_words)
            if vocab:
                results[title[:30]] = pd.DataFrame({
                    '单词': vocab,
                    '出现次数': [vocab.count(w) for w in vocab]
                })
            logger.chapter_progress(idx, len(chapters))

        # 保存结果
        FileManager.save_vocabulary(results, settings.OUTPUT_PATH)
        logger.log(f"处理完成，结果保存至: {settings.OUTPUT_PATH}")

    except BookProcessingError as e:
        logger.log(f"处理失败: {str(e)}", logging.ERROR)
    except Exception as e:
        logger.log(f"未知错误: {str(e)}", logging.CRITICAL)

if __name__ == "__main__":
    main()
